<template>
	<view class="page">
		<canvas class="canvas" v-if="isShow" :style="{width:`${canvasWidth}px`,height:`${canvasHeight}px`}"
			:canvas-id="canvasId"></canvas>
		<view class="tool">
			<u-button @click="nextImg" :custom-style="buttonCustomStyle" text="下一张"
				color="linear-gradient(to right, #232526, #414345)"></u-button>
			<u-button @click="save" :custom-style="buttonCustomStyle" text="保存图片"
				color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"></u-button>

		</view>
	</view>
</template>

<script setup lang="ts">
	import { onMounted, reactive, ref, watch } from "vue";
	import { getImgBase64, drawRoundedRect, drawText, getSystemInfo } from "@/utils/canvas";
	import { imageList } from './utils'
	import type { ImageListType } from './utils'
	import { getAuthorize } from "@/utils";
	// 按钮样式
	const buttonCustomStyle = reactive({
		width: '49%',
	});
	// const color = '#f7f6ff'
	const offsetNumber : number = 20;
	const listHeight : number = 66;
	const context = ref(null)
	const pageColor = ref(imageList[0].pageColor)
	const canvasId = ref<string>(String(`canvasId${new Date().getTime()}`))
	const isShow = ref<boolean>(false)
	const imageObj = ref<ImageListType>(imageList[0])
	const imgTemp = ref<string>(wx.env.USER_DATA_PATH + `/${new Date().getTime()}-temp.png`) //图片存储的临时路径
	const canvasWidth = ref<number>(0)// canvas宽度
	const canvasHeight = ref<number>(0)// canvas宽度
	const canvasWidthRate = ref<number>(0.8)//canvas基于屏幕宽度占比,随便设置，我这里设置占屏幕宽度的百分之八十
	// 绘制图片,并转成base64
	const drawBgImg = async () => {
		// 图片临时地址重新赋值，避免图片加载路径都是一样的
		imgTemp.value = wx.env.USER_DATA_PATH + `/${new Date().getTime()}-temp.png`
		const ctx = context.value
		const { imgUrl, imageWidth, imageHeight } = await getImgBase64({
			src: imageObj.value.imageSrc,
			canvasWidth: canvasWidth.value,
			filePath: imgTemp.value
		})
		canvasHeight.value = canvasHeight.value + imageHeight //重新计算画布总高度
		// 填充背景矩阵
		drawRoundedRect(ctx, 0, 0, canvasWidth.value, canvasHeight.value, {
			fillColor: imageObj.value.bgColor,
			leftBottom: true,
			leftTop: true,
			rightBottom: true,
			rightTop: true,
			r: 5
		})
		// 图片如何居中呢？
		// 当前画布宽度 - 图片宽度 = 空出来的间隙
		// 图片居中 = 空出来的间隙 / 2 = x 轴起点 x = canvasWidth.value - imageWidth) / 2
		ctx.drawImage(imgUrl, (canvasWidth.value - imageWidth) / 2, offsetNumber, imageWidth, imageHeight);
	}
	// 绘制文字
	const drawTxt = async () => {
		const ctx = context.value
		const offsetY = canvasHeight.value
		// 填充矩形背景
		drawRoundedRect(ctx, 0, canvasHeight.value, canvasWidth.value, listHeight, {
			fillColor: imageObj.value.bgColor,
		});
		// 绘制文字
		drawText({
			ctx,
			text: imageObj.value.name,
			fillStyle: '#000000',
			fontSize: 22,
			x: (canvasWidth.value / 2),
			y: offsetY + 25,
			center: true
		})
		// 绘制文字
		drawText({
			ctx,
			text: imageObj.value.desc,
			fillStyle: '#000000',
			fontSize: 16,
			x: (canvasWidth.value / 2),
			y: offsetY + 25 + 25,
			center: true
		})
		//画布高度重新计算
		canvasHeight.value = canvasHeight.value + listHeight
	}
	// 初始化canvas
	const initCanvas = async () => {
		try {
			uni.showLoading()
			const { windowWidth } : any = await getSystemInfo()
			const ctx = context.value
			canvasHeight.value = offsetNumber;//初始化高度
			canvasWidth.value = windowWidth * canvasWidthRate.value//初始化宽度
			await drawBgImg()
			await drawTxt()
			ctx.draw()
		} finally {
			uni.hideLoading()
		}

	}
	onMounted(() => {
		isShow.value = true
	})
	watch(isShow, () => {
		if (isShow.value) {
			canvasId.value = String(`canvasId${new Date().getTime()}`)//由于存在多次绘制，避免ID重复，需要重新赋值
			context.value = uni.createCanvasContext(canvasId.value)//由于存在多次绘制，所以每次都重新创建新的画布实例
			initCanvas()

		}

	})
	// 下一张图
	const nextImg = () => {
		isShow.value = false
		imageObj.value = imageList[imageObj.value.id + 1] ?? imageList[0]
		pageColor.value = imageObj.value.pageColor
		setTimeout(() => {
			isShow.value = true
		}, 100)
	}
	// 图片添加到相册
	const addIamgeToAlbum = async () => {
		try {
			const { tempFilePath } = await uni.canvasToTempFilePath({
				canvasId: canvasId.value,
			});
			console.log('tempFilePath', tempFilePath);
			await uni.saveImageToPhotosAlbum({
				filePath: tempFilePath
			})
			uni.showToast({
				title: '保存成功！'
			})
		} catch {

		}

	}
	// 保存
	const save = async () => {
		try {
			uni.showLoading()
			// 获取用户设置
			const { authSetting } = await uni.getSetting()
			// 没有权限的时候
			if (!authSetting['scope.writePhotosAlbum']) {
				await getAuthorize('scope.writePhotosAlbum', {
					title: '请授权保存到相册',
					callback: addIamgeToAlbum
				})
				return
			}
			addIamgeToAlbum()
		} catch (err) {
		} finally {
			uni.hideLoading()
		}

	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: v-bind(pageColor);
		height: 100vh;
		overflow: hidden;

		.canvas {
			margin: 20px auto 0;
		}

		.tool {
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;


		}
	}
</style>